package com.rq.base.ui;

import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;


import com.rq.base.BASE;
import com.rq.base.R;
import com.rq.base.net.RequestType;
import com.rq.base.ui.common.CommonDialog;
import com.rq.base.ui.impl.WelcomeImpl;
import com.rq.base.util.AppUtils;
import com.rq.base.util.LOG;
import com.rq.base.util.LanguageUtil;
import com.rq.base.util.SPUtil;
import com.rq.base.util.ToastUtil;

import java.util.Locale;

import androidx.annotation.NonNull;

/**
 * 开屏页
 */

public class WelcomeController extends BaseController implements
        CommonDialog.OnConfirmClickListener, CommonDialog.OnDialogInterface {


    WelcomeImpl page;

    @Override
    public void onViewCreated(Bundle savedInstanceState) {
        super.onViewCreated(savedInstanceState);
        toNextView();
        LOG.e("WelcomeController", "onViewCreated.45:" + BASE.getLockScreenOrientation());
        page.init(this);
        refuseLanguage();
    }

    private void refuseLanguage() {
        Resources resources = getActivity().getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        Configuration config = resources.getConfiguration();
        String save = SPUtil.getString("language");
        if (TextUtils.isEmpty(save)) {
            return;
        }
        Locale saveLo = new LanguageUtil().getLocale();
        config.setLocale(saveLo);
        resources.updateConfiguration(config, dm);
//        page.setBackLanInfo(new LanguageUtil(getActivity()).getOption());
        //        HttpManager.setLanguage(WelcomeController.this, new LanguageUtil().getOption());
    }


    @Override
    public int getLayoutId() {
        try {
            this.page = (WelcomeImpl) BASE.getWelcomeClazz().newInstance();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return this.page.getLayoutId();
    }


    private void toNextView() {
        long time = page.getAutoSkipTime();
        if (time > 0) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    skip();
                }
            }, time);
        }
        //        new Thread(new Runnable() {
        //            @Override
        //            public void run() {
        //                initQQWeb();
        //            }
        //        }).start();
    }
    //
    //    private void initQQWeb() {
    //        BASE.initQQWeb(getContext());
    //    }

    boolean needUpload = false;
    private boolean hasSKip = false;

    private void skip() {
        if (hasSKip) {
            return;
        }
        if (this.downProgress > 0) {
            return;
        }
        if (needUpload) {
            return;
        }
        if (!isShow()) {
            return;
        }
        this.hasSKip = true;
        welcomeSkip();
    }

    @Override
    public <T> void onResponseSucceed(@NonNull RequestType type, T data) {
        if (!hasSKip && page.isSkipData(this, type, data)) {
            this.needUpload = needStopToDownload();
            return;
        }
        super.onResponseSucceed(type, data);
    }

    @Override
    public <T> void onResponseError(@NonNull RequestType type, T data) {
        if (!hasSKip && page.isSkipData(this, type, null)) return;
        super.onResponseError(type, data);
    }

    protected void welcomeSkip() {
        if (BASE.getLoginHelper() != null) {
            skip(BASE.getLoginHelper());
        } else {
            page.skip(this);
        }
    }

    /**
     * @return 是否需要更新
     */
    private boolean needStopToDownload() {
        if (this.page == null || TextUtils.isEmpty(page.getUpdatePath())) {
            return false;
        }
        if (!TextUtils.equals(AppUtils.getVersionName(), page.getNetVersionName())) {
            if (BASE.isRQ()) {
                ToastUtil.show("测试，跳过更新");
                return false;
            }
            CommonDialog dialog = new CommonDialog.Builder(getActivity()).setContentView(R.layout.dialog_download)
                    .addString(R.id.dialog_title, "更新提示")
                    .addOnClick(this, R.id.dialog_confirm)
                    .addOnClick(this, R.id.dialog_cancel)
                    .addString(R.id.dialog_content, page.getVersionDescribe()).create();
            LOG.e("WelcomeController", "needStopToDownload.164:" + page.isCancelAble());
            dialog.setCancelable(page.isCancelAble());
            if (page.isCancelAble()) {//可选更新
                dialog.setBtnShow(true, true);
            } else {//必须更新
                dialog.setBtnShow(false, true);
            }
            dialog.show(page);
            dialog.setClickListener(this);
            return true;
        }
        return false;
    }

    int downProgress = 0;

    @Override
    public void onClick(CommonDialog commonDialog, int vId) {
        if (vId == R.id.dialog_confirm || vId == R.id.dialog_cancel) {
            onClickConfirm(vId == R.id.dialog_confirm, null);
        }
    }

    @Override
    public void onClickConfirm(boolean isConfirm, Object data) {
        if (isConfirm) {
            this.needUpload = true;
            if (page != null) {
                page.clickDownload(getContext(), page.getUpdatePath(), page.getNetVersionName() + ".apk");
            }
//            PermissionUtil.selectLocalFile(getActivity(), new PermissionUtil.OnPermissionListener() {
//                @Override
//                public void onPermissionOk() {
//                    Intent intentService = DownloadIntentService
//                            .getTask(getContext(), page.getUpdatePath(), page.getNetVersionName() + ".apk",WelcomeController.this);
//                    getActivity().startService(intentService);
//                }
//            });
        } else {
            this.needUpload = false;
            downProgress = 0;
            skip();
        }
    }


//    @Override
//    public void onProgress(int progress) {
//        LOG.e("WelcomeController", "onProgress:" + progress);
//        downProgress = progress;
//        setData2View(R.id.welcome_progress_text, "下载进度" + downProgress + "%");
//    }
//
//    @Override
//    public void onCompleted(File file) {
//        downProgress = 100;
//        DownloadIntentService.installApp(getActivity(), file, getActivity().getPackageName() + ".fileProvider");
//    }
//
//    @Override
//    public void onError() {
//        ToastUtil.show("下载异常");
//    }

    @Override
    public boolean justLayout() {
        return true;
    }

    @Override
    public boolean underStatusBar() {
        return true;
    }


}
